package com.heima.article.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemakerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.LoadBehaviorDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.article.vos.LoadBehaviorVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.heima.common.constants.ArticleConstants.*;

/**
* @author 马毅爽
* @description 针对表【ap_article(文章信息表，存储已发布的文章)】的数据库操作Service实现
* @createDate 2023-12-01 20:51:54
*/
@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle>
    implements ApArticleService{

    @Autowired
    private ApArticleMapper articleMapper;

    private final static short MAX_PAGE_SIZE = 50;

    @Override
    public ResponseResult load(Short loadType, ArticleHomeDto dto) {
        // 1. 校验参数
        // 分页参数校验
        Integer size = dto.getSize();
        if (size == null || size == 0){
            size = 10;
        }
        // 分页的值不超过50
        size = Math.max(size,MAX_PAGE_SIZE);
        // 校验参数
        if (!loadType.equals(LOADTYPE_LOAD_MORE) && !loadType.equals(LOADTYPE_LOAD_NEW)){
            loadType = LOADTYPE_LOAD_MORE;
        }
        // 频道参数校验
        if (StrUtil.isBlank(dto.getTag())) {
            dto.setTag(DEFAULT_TAG);
        }
        // 时间校验
        if (dto.getMaxBehotTime() == null)dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null)dto.setMinBehotTime(new Date());

        // 2. 查询文章列表
        List<ApArticle> list = articleMapper.loadArticle(loadType,dto);

        return ResponseResult.okResult(list);
    }


    @Override
    public ResponseResult load2(Short loadType, ArticleHomeDto dto, boolean firstPage) {
        if (firstPage){
            String jsonStr = cacheService.get(HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StrUtil.isNotBlank(jsonStr)){
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                return ResponseResult.okResult(hotArticleVoList);
            }
        }
        return load(loadType, dto);
    }

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ArticleFreemakerService articleFreemakerService;

    @Override
    public ResponseResult saveArticle(ArticleDto dto) {

        // 1. 检查参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApArticle apArticle = BeanUtil.copyProperties(dto, ApArticle.class);

        // 2. 判断是否存在id
        if (dto.getId() == null){
            // 2.1 不存在id 保存 文章 文章配置 文章内容
            // 保存文章
            save(apArticle);

            // 保存配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //保存 文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);

        }else {
            // 2.2 存在id 修改 文章 文章内容
            // 修改文章
            updateById(apArticle);

            // 修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(new LambdaQueryWrapper<ApArticleContent>().eq(ApArticleContent::getArticleId, dto.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);

        }

        // 异步调用 生成静态文件上传到minio中
        articleFreemakerService.buildArticleToMinio(apArticle, dto.getContent());



        // 3. 结果返回 文章的id
        return ResponseResult.okResult(apArticle.getId());
    }

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult loadBehavior(LoadBehaviorDto dto) {
        // 1. 检查参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 是否登录
        ApUser apUser = AppThreadLocalUtil.getUser();
        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3. 获取数据
        Object like = cacheService.hGet("LIKE-BEHAVIOR-" + dto.getArticleId(), apUser.getId().toString());
        Object unlike = cacheService.hGet("UNLIKE-BEHAVIOR-" + dto.getArticleId(), apUser.getId().toString());
        Object follow = cacheService.hGet("FOLLOW-BEHAVIOR-" + dto.getArticleId(), apUser.getId().toString());
        Object collection = cacheService.hGet("COLLECTION-BEHAVIOR-" + dto.getArticleId(), apUser.getId().toString());

        LoadBehaviorVo loadBehaviorVo = new LoadBehaviorVo();
        loadBehaviorVo.setIslike(like != null);
        loadBehaviorVo.setIsunlike(unlike != null);
        loadBehaviorVo.setIsfollow(follow != null);
        loadBehaviorVo.setIscollection(collection != null);
        return ResponseResult.okResult(loadBehaviorVo);
    }

    @Override
    public void updateScore(ArticleVisitStreamMess visitStreamMess) {
        // 1. 更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(visitStreamMess);
        // 2. 计算文章的得分值
        Integer score = computeScore(apArticle);
        score *= 3;
        // 3. 替换当前文章对应频道的热点数据
        replaceDataToRedis(HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId(), apArticle, score);
        // 4. 替换推荐对应的热点数据
        replaceDataToRedis(HOT_ARTICLE_FIRST_PAGE + DEFAULT_TAG, apArticle, score);
    }

    private void replaceDataToRedis(String key, ApArticle apArticle, Integer score) {
        String articleListAllStr = cacheService.get(key);
        if (StrUtil.isNotBlank(articleListAllStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListAllStr, HotArticleVo.class);

            boolean flag = true;
            // 如果缓存中存在改文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }
            // 如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hotArticleVo = BeanUtil.copyProperties(apArticle, HotArticleVo.class);
                        hotArticleVo.setScore(score);
                        hotArticleVoList.add(hotArticleVo);
                    }
                } else {
                    HotArticleVo hotArticleVo = BeanUtil.copyProperties(apArticle, HotArticleVo.class);
                    hotArticleVo.setScore(score);
                    hotArticleVoList.add(hotArticleVo);
                }
            }
            // 缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(key, JSON.toJSONString(hotArticleVoList));
        }
    }

    private ApArticle updateArticle(ArticleVisitStreamMess visitStreamMess) {
        ApArticle apArticle = getById(visitStreamMess.getArticleId());
        apArticle.setCollection(apArticle.getCollection() == null ? 0 : apArticle.getCollection() + visitStreamMess.getCollect());
        apArticle.setComment(apArticle.getComment() == null ? 0 : apArticle.getComment() + visitStreamMess.getComment());
        apArticle.setLikes(apArticle.getLikes() == null ? 0 : apArticle.getLikes() + visitStreamMess.getLike());
        apArticle.setViews(apArticle.getViews() == null ? 0 : apArticle.getViews() + visitStreamMess.getView());
        updateById(apArticle);
        return apArticle;
    }

    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if (apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}




